package com.xhs.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * @desc: WebSocket 拦截器
 * @projectName: spring-boot-websocket
 * @author: xhs
 * @date: 2025-03-24 周一 23:33
 * @version: JDK 1.8
 */
@Slf4j
@Component
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    /**
     * 握手之前触发
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return boolean true表示握手成功,false表示握手失败
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        log.info("WebSocket握手前");
        return true;
    }

    /**
     * 握手之后触发
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param exception 入参
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        if (exception != null) {
            // 若握手过程中出现异常，记录错误日志
            log.error("WebSocket 握手过程中出现异常:{}", exception.getMessage());
        } else {
            // 握手成功，记录日志
            log.info("WebSocket 握手成功");
        }
    }
}
